<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models\Api;

use App\Models\Env\CommonHeader;
use App\Models\Env\Host;
use App\Models\Env\HostEnv;
use App\Models\Module\ProductModule;
use App\Models\Projects\Product;
use App\Models\Projects\Project;
use App\Models\Projects\ProjectCate;
use App\Models\TestApi\TestApi;
use Carbon\Carbon;
use App\Models\Eloquent;
use App\Models\Meimei\Traits\SignOssUrlTrait;
use App\Models\Meimei\Traits\ExplodeTrait;

/**
 * Class QtpApi
 *
 * @property int $id
 * @property int $cate_id
 * @property int $project_id
 * @property int $product_id
 * @property int $f_module_id
 * @property int $s_module_id
 * @property int $host_id
 * @property int $method_type
 * @property string $name
 * @property string $api
 * @property string $remark
 * @property string $note
 * @property string $tags
 * @property string $created_adminer
 * @property string $updated_adminer
 * @property int $sort
 * @property int $enable
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 *
 * @package App\Models
 */
class Apis extends Eloquent
{
    use ExplodeTrait;
    use SignOssUrlTrait;
    protected $explode = ['tags'];

    protected $table = 'apis';

    protected $casts = [
		'cate_id' => 'int',
		'project_id' => 'int',
		'product_id' => 'int',
		'f_module_id' => 'int',
		's_module_id' => 'int',
		'host_id' => 'int',
		'method_type' => 'int',
		'sort' => 'int',
		'enable' => 'int'
	];

    protected $fillable = [
        'cate_id',
        'project_id',
        'product_id',
        'f_module_id',
        's_module_id',
        'host_id',
        'method_type',
        'name',
        'api',
        'remark',
        'note',
        'tags',
        'created_adminer',
        'updated_adminer',
        'sort',
        'enable',
    ];

    const METHOD_TYPE_POST = 1;
    const METHOD_TYPE_GET = 2;
    const METHOD_TYPE_OPTIONS = 3;

    const METHOD_TYPE_PUT = 4;
    const METHOD_TYPE_HEAD = 5;
    const METHOD_TYPE_DELETE = 6;

    const METHOD_TYPE_UPDATE = 7;
    const METHOD_TYPE_TRACE = 8;
    const METHOD_TYPE_CONNECT = 9;
    public static $method_type_maps = [
        self::METHOD_TYPE_POST => 'POST',
        self::METHOD_TYPE_GET => 'GET',
        self::METHOD_TYPE_OPTIONS => 'OPTIONS',
        self::METHOD_TYPE_PUT => 'PUT',
        self::METHOD_TYPE_HEAD => 'HEAD',
        self::METHOD_TYPE_DELETE => 'DELETE',
        self::METHOD_TYPE_UPDATE => 'UPDATE',
        self::METHOD_TYPE_TRACE => 'TRACE',
        self::METHOD_TYPE_CONNECT => 'CONNECT',
    ];

    public function label()
    {
        $this->cate_name = ProjectCate::find($this->cate_id)->name ?? '';
        $this->project_name = Project::find($this->project_id)->name ?? '';
        $this->product_name = Product::find($this->product_id)->name ?? '';
        $this->f_module_name = ProductModule::find($this->f_module_id)->name ?? '';
        $this->s_module_name = ProductModule::find($this->s_module_id)->name ?? '';
        $this->method_type_lable = self::$method_type_maps[$this->method_type] ?? '未知';
        $this->header_count = (int) ApisHeader::where("api_id", $this->id)->count();
        $this->param_count = (int) ApisParam::where("api_id", $this->id)->count();
        $this->sample_value_count = (int) SampleValue::where("api_id", $this->id)->count();
        $this->validator_count = (int) ApisValidator::where("api_id", $this->id)->count();
        $this->test_sum = TestApi::where('api_id', $this->id)->count(); // 测试历史条数
        list($this->host_env, $this->host_url) = ['', ''];
        if($this->host_id > 0) {
            $HostEnv = HostEnv::find($this->host_id);
            list($this->host_env, $this->host_url) = [
                $HostEnv->name ?? '',
                Host::where('host_env_id', $HostEnv->id)->where('enable', 1)->first()->http ?? ''
            ];
        }

        $this->headers = self::getHeaders($this) ?: [];
        return $this;
    }


    public static $fillables = [
        'cate_id' => '分类ID',
        'project_id' => '项目ID',
        'product_id' => '产品ID',
        'f_module_id' => '主模块ID',
        's_module_id' => '子模块ID',
        'host_id' => '公共HOST.ID',
        'method_type' => '请求方式(1POST,2GET)',
        'name' => '接口名称',
        'api' => '接口',
        'remark' => '说明',
        'note' => '备注',
        'tags' => '标签',
        'created_adminer' => '创建人',
        'updated_adminer' => '更新人',
        'sort' => '排序',
        'enable' => '状态',
    ];

    public static function getApiIdsBySids(array $sids): ?array
    {
        $api_ids = [];
        foreach($sids as $sid) {
            $sidsf = self::where('s_module_id', $sid)
                ->select(['id', 'sort'])
                ->where('enable', 1)
                ->orderByDesc('sort')
                ->pluck('id')?->toArray();
            if(empty($sidsf)) {
                continue;
            }
            $api_ids[] = $sidsf;
        }
        if(empty($api_ids)) {
            return [];
        }
        $fun = function ($a) {
            $c = [];
            foreach ($a as $b) {
                foreach ($b as $d) {
                    $c[] = $d;
                }
            }
            return $c;
        };
        return $fun($api_ids);
    }

    public static function getHeaders(self $api): ?array
    {
        $common_headers = CommonHeader::select('key', 'value')->where('product_id', $api->product_id)->where('enable', 1)->get()?->toArray() ?: [];
        $api_headers = ApisHeader::select('key', 'value')->where('api_id', $api->id)->get()?->toArray() ?: [];

        $headers_e = array_merge($common_headers, $api_headers);
        if(empty($headers_e)) {
            return [];
        }
        $headers = [];
        foreach($headers_e as $v) {
            $headers[$v['key']] = $v['value'];
        }
        return $headers;
    }
}
